package com.example.battery;


import java.lang.reflect.Method;



import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends Activity  {
	
	 int notifyID=1;
	
	
	Button powersave,wifi,brightness,dataconnection,gps,autoRotation,bluetooth,vibration,battery_level,optim;
    
    Button silentloud,save,cancel;

	SeekBar seekBar,seekBars;
    
    AudioManager mobilemode;
    
    ImageView charger;

	
public static final String Pref_Names = "battery_doctor";
	
	public static final String wifi_key = "wifi";
	public static final String bluetooth_key = "bluetooth";
	public static final String brightness_key = "brightness";
	public static final String vibration_key = "vibration";
	public static final String mobile_key = "mobiledata";
	
	public boolean wifi_enabled = false;
	public boolean bluetooth_enabled = false;
	public boolean brightness_enabled = false;
	public boolean vibration_enabled = false;
	public boolean mobiledata_enabled = false;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		
		powersave=(Button)findViewById(R.id.button_power);
		wifi=(Button)findViewById(R.id.button_wifi);
		brightness=(Button)findViewById(R.id.button_brightness);
		dataconnection=(Button)findViewById(R.id.button_dataconnection);
		gps=(Button)findViewById(R.id.button_gps);
		autoRotation=(Button)findViewById(R.id.button_screenrotation);
		silentloud=(Button)findViewById(R.id.button_silentloud);
		vibration=(Button)findViewById(R.id.button_vibration);
		bluetooth=(Button)findViewById(R.id.button_bluetooth);
		battery_level=(Button)findViewById(R.id.button10);
		optim=(Button)findViewById(R.id.button11);
		save=(Button)findViewById(R.id.button_save);
		charger=(ImageView)findViewById(R.id.charger);
		
		getSavedSettings();
		
		System.out.println("raj wifi_enabled: "+wifi_enabled);
		System.out.println("raj bluetooth_enabled: "+bluetooth_enabled);
		System.out.println("raj brightness_enabled: "+brightness_enabled);
		System.out.println("raj vibration_enabled: "+vibration_enabled);
		System.out.println("raj mobiledata_enabled: "+mobiledata_enabled);
		
	 getBatteryPercentage();
	 portrait(null);
	 
	 optim.setOnClickListener(new OnClickListener() {
		
		

		@Override
		public void onClick(View v) {
			
			//Toast.makeText(getApplicationContext(), "Hi Ajay",2000).show();
			
			if(wifi_enabled)
			{
				setwifiEnabled(false);
				wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_blue, 0, 0);
				
			}
			 if(bluetooth_enabled)
			{
				 setBluetooth(false);
				 bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_blutooth, 0, 0);
				
			}
			 if(brightness_enabled)
			{
				
				//setBrightness(false);
				
				int progress = 0;
					//public void onStopTrackingTouch(SeekBar seekBar) {
					android.provider.Settings.System.putInt(getContentResolver(),
							android.provider.Settings.System.SCREEN_BRIGHTNESS,
							progress);
				
				
			}

			 if(vibration_enabled)
			{
				setVibrationMode(false);
				
			}
			 if(mobiledata_enabled)
			{
				 setMobileDataEnabled(false);
				 dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_arrow, 0, 0);
				
			}
		}
	});
	 
	 
	 
	 
	
     mobilemode = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
     
		 if(isWifiEnabled(getApplicationContext()))
		 {
			wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_green, 0, 0);			
		 }
		 else
		 {
			wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_blue, 0, 0);			
		 }
	
		 if( !isBluetoothEnabled())
		 {
			   
		 bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_blutooth, 0, 0);
			   
		 }
		 else
		 {
			 
		 bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_blutooth, 0, 0);
			   
		 }
		 System.out.println("raj 11111111111");
		 
		 if( !isDataNetworkEnabled())
		 {
			 
		 System.out.println("raj 2222222222222222");
	     dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_arrow, 0, 0);
		// setMobileDataEnabled(false);   
		 }
		 else			 
		 {
		 System.out.println("raj 33333333333333");
		 dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_arrow, 0, 0);
		// setMobileDataEnabled(true);
		 }
		 
		 if(mobilemode.getRingerMode() == AudioManager.RINGER_MODE_SILENT)
		 {
			 silentloud.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.silentmode_blue, 0, 0);
			 silentloud.setText("silent");
		 }
		 else 
		 {
			 silentloud.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.phone_rignmode_green, 0, 0);
			 silentloud.setText("normal");
		 }
		 
		 if(mobilemode.getRingerMode() == AudioManager.RINGER_MODE_NORMAL)
		 {
			 
		// mobilemode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
		 
		 vibration.setText("Vibrate On");
		 }
		 
		 else{
		 
		 silentloud.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.silentmode_blue, 0, 0);
		 silentloud.setText("silent");
				
		 }
		 
		 if(android.provider.Settings.System.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0) == 1)
		 {
	     android.provider.Settings.System.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0);
		  
		 autoRotation.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.rotation_green, 0, 0);
	     }
	     else
	     {
   	     android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
		   
		 autoRotation.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.rotation_blue, 0, 0);
	     }
		 

	}
		 
		
	
	
	protected void setBrightness(boolean b) {
		// TODO Auto-generated method stub
		
	}



	protected void setVibrationMode(boolean b) {
		// TODO Auto-generated method stub
		
		if(mobilemode.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE){
			
			//setVibrationMode(false);
			
		}
		
	}



	protected void stopService(Object wifi_enabled2) {
		// TODO Auto-generated method stub
		
	}



	//Setting profile mode//
	 public void setProfileMode(View v){
	 
	 {
		 if(mobilemode.getRingerMode() == AudioManager.RINGER_MODE_SILENT)
		 {
			 
			 mobilemode.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
			 vibration.setText("Vibrate Off");
			 silentloud.setText("Normal");
			// mobilemode.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
			 silentloud.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.phone_rignmode_green, 0, 0);
		 }
		 else 
		 {
			 silentloud.setText("Silent");
			 mobilemode.setRingerMode(AudioManager.RINGER_MODE_SILENT);
			 silentloud.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.silentmode_blue, 0, 0);
			 //silentloud.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.phone_rignmode_green, 0, 0);
		 }
	 }
	 
		 
		 
			
	 }
	 
	 // Setting Vibration mode //
	 public void setVibrationMode(View v){
	
	Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	 
				if(mobilemode.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE)
				{
					
					
					 mobilemode.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
					 vibration.setText("Vibrate Off");
					 silentloud.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.phone_rignmode_green, 0, 0);
					 silentloud.setText("Normal");
					 
				}
				else 
				{
					vibration.setText("Vibrate On");
					 vibrator.vibrate(500);
					mobilemode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
					 silentloud.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.silentmode_blue, 0, 0); 	 
					 silentloud.setText("Silent");
					
					 
				}
				
				
				
		 }
	 
	// Power Saving Activity //
	public void powersave (View v){
		
		Intent i = new Intent(this,PowerSaveSettingsActivity.class);
	    startActivity(i);
	}
	
	// Setting GPS Activity //
	public void setgps(View v){
		
		Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);//getApplicationContext(),GpsActivity.class);
		
		startActivity(gps);
	}
	
	// Checking Wifi Status //
	public void setwifiEnabled(boolean enable)
	{		
		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		wifi.setWifiEnabled(enable);
	}
	
    public static boolean isWifiEnabled(Context context) {
        boolean result = false;
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        android.net.NetworkInfo activeNetwork = connectivityManager
                .getActiveNetworkInfo();
        if (activeNetwork != null
                && (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)) {
           // if (activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
                result = true;
                activeNetwork.getDetailedState();
            } else {
            	 result = false;
            }
        
        return result;
    }
    public void setBluetooth(boolean enable)
    {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(enable)
        	bluetoothAdapter.enable();
        else
        	bluetoothAdapter.disable();
    } 
    
    public static boolean isBluetoothEnabled() 
    {
    	BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter.isEnabled();
    }
    
    
    public boolean isDataNetworkEnabled() 
    {
        boolean result = false;
        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        System.out.println("raj 444444444444444: "+activeNetwork);
        
	       
	        	if(activeNetwork.isConnected())
		        {
	        		 System.out.println("raj 666666666666");
		            result = true;
		        }
		        else 
		        {
		        	System.out.println("raj 7777777777777");
		           	result = false;
		        }
	        	 System.out.println("raj data enabled: "+result);
	             
	             return result; 
        }
    
    public void setMobileDataEnabled(boolean enable)
    {
        try
        {       
            ConnectivityManager dataManager;
            dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
            dataMtd.setAccessible(true);
            dataMtd.invoke(dataManager, enable);
        }
        catch(Exception ex)
        {
            System.out.println("raj Error in enabling the MObile Data: "+ex);
        }             
    }
   
    public void setwifi(View v)
    {    	
    	
		if(!isWifiEnabled(getApplicationContext()))
		{
			wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_green, 0, 0);
			setwifiEnabled(true);
		}
		else
		{
			wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_blue, 0, 0);
			setwifiEnabled(false);
		}
    }
    
   public void setBluetooth(View v){
	   
	   if( !isBluetoothEnabled()){
		   
		   bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_blutooth, 0, 0);
		   setBluetooth(true); 
	   }
	   else
	   {
		   bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_blutooth, 0, 0);
		   setBluetooth(false); 
	   }
   } 
   
   public void dataconnection(View v){
	   
	   
		 if(isDataNetworkEnabled())
		 {
		   
		   dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_arrow, 0, 0);
		   setMobileDataEnabled(false);
	   }
	   else 
	   {
		   dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_arrow, 0, 0);
		   setMobileDataEnabled(true);
	   }
	   
   }
   
   
   // Method for screen AutoRotation
  public void autoRotation(View v)
  {
	
	 if(android.provider.Settings.System.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0) == 1)
	    {
	    android.provider.Settings.System.putInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0);
	    Toast.makeText(MainActivity.this, "Rotation OFF", Toast.LENGTH_SHORT).show();
	    autoRotation.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.rotation_blue, 0, 0);
	    }
	    else{
	    android.provider.Settings.System.putInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
	    Toast.makeText(MainActivity.this, "Rotation ON", Toast.LENGTH_SHORT).show();
	    autoRotation.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.rotation_green, 0, 0);
	    }
    }
 
 
 public void setBrightness(View v){
	 
	 final Dialog dialog = new Dialog(this);
	 dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	 //dialog.setTitle("Adjust Brightness");
	 dialog.setContentView(R.layout.brightnessalert);
	 dialog.show();
 
	 SeekBar brightness_level = (SeekBar)dialog.findViewById(R.id.brightness);
	 Button brightnessok = (Button)dialog.findViewById(R.id.button_adjust);
	 
	 brightnessok.setOnClickListener(new OnClickListener() {
		
		@SuppressLint("CommitPrefEdits")
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "Saved Successfully...", Toast.LENGTH_LONG).show();
			
			 dialog.dismiss();
		}
	});
	
	 
	
	 brightness_level.setMax(255);
	 
	 float curBrightnessValue = 0;
		try {
			curBrightnessValue = android.provider.Settings.System.getInt(
					getContentResolver(),
					android.provider.Settings.System.SCREEN_BRIGHTNESS);
		} catch (SettingNotFoundException e) {
			e.printStackTrace();
		}
		

		int screen_brightness = (int) curBrightnessValue;
		brightness_level.setProgress(screen_brightness);
		brightness_level.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			int progress = 0;
			@Override
			public void onProgressChanged(SeekBar seekBar, int progresValue,
					boolean fromUser) {
				progress = progresValue;
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				android.provider.Settings.System.putInt(getContentResolver(),
						android.provider.Settings.System.SCREEN_BRIGHTNESS,
						progress);
			}
		});
		
}
 
 
	// Method for battery Status //
   public void getBatteryPercentage() {
	   
	 BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
		 
		 public void onReceive(Context context, Intent intent) {
            // context.unregisterReceiver(this);
        	 @SuppressWarnings("unused")
			String action = intent.getAction();
        	 
        	 if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction()))
        	 {
        		 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
        		 
        		 if(status == BatteryManager.BATTERY_STATUS_CHARGING)
        		 {
        			 //charger.setActivated(true);
        			 charger.setVisibility(View.VISIBLE);
        			// battery_level.setCompoundDrawablesWithIntrinsicBounds(R.drawable.plug_horizental_black,0,0,0);
        			 System.out.println("raj chrging.....");
        			 battery_level.setText("Charging");
        			// int plugged = intent.getIntExtraw(BatteryManager.EXTRA_PLUGGED, 0);
        			// charger.setImageResource(R.drawable.plug_horizental_black);
        			 
        		 }
        		 
        		 else //if(status == BatteryManager.BATTERY_STATUS_NOT_CHARGING)
        			 
        		 {
        			 //charger.setActivated(false);
        			 charger.setVisibility(View.GONE);
        			// battery_level.setCompoundDrawablesWithIntrinsicBounds(0,0,0,0); 
        			 System.out.println("raj not chrging.....");
        			// charger.setImageResource(R.drawable.plug);
        		 }
        	 }
        	 
        	 
        	 
            // String action = intent.getAction();
             
            // int icon_small = intent.getIntExtra(
            //         BatteryManager.EXTRA_ICON_SMALL, 0);
           //  int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
      	   
      	   // battery_level.setCompoundDrawablesWithIntrinsicBounds(0,icon_small, 0, 0);
   	    	
             
            // battery_level.setCompoundDrawablesWithIntrinsicBounds(0,icon_small, 0, 0);
             
          // if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
        	  
     	   // battery_level.setBackgroundResource(R.drawable.blue_arrow); 
     	        // Do something when power connected
        	  // battery_level.setCompoundDrawablesWithIntrinsicBounds(R.drawable.plug_horizental_black,0,0,0);
     		  // battery_level.setText("Charging");
     		
     	   // }
     	   // else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
     	   //     // Do something when power disconnected
     	    	
     	   // }
             int currentLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
             int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
             int level = -1;
             if (currentLevel >= 0 && scale > 0) {
                 level = (currentLevel * 100) / scale;
             }
            
             battery_level.setText("Level : "+level+"%");
             if(level <= 20 )
             {
            	 battery_level.setBackgroundResource(R.drawable.single_point);
             }
             else if(level <= 40 )
             {
            	 battery_level.setBackgroundResource(R.drawable.double_point); 
             }
             else if(level <= 60 )
             {
            	 battery_level.setBackgroundResource(R.drawable.three_point); 
             }
             else if(level <= 80 )
             {
            	 battery_level.setBackgroundResource(R.drawable.four_point); 
             }
             else if(level <= 100 )
             {
            	 battery_level.setBackgroundResource(R.drawable.full_battery); 
             }
         }
     };
    
     IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
     registerReceiver(batteryLevelReceiver, batteryLevelFilter);
	 }
   public void getSavedSettings()
	{
		SharedPreferences preferences = getApplicationContext().getSharedPreferences(Pref_Names, MODE_PRIVATE);
		wifi_enabled = preferences.getBoolean(wifi_key, false);
		bluetooth_enabled = preferences.getBoolean(bluetooth_key, false);
		brightness_enabled = preferences.getBoolean(brightness_key, false);
		vibration_enabled = preferences.getBoolean(vibration_key, false);
		mobiledata_enabled = preferences.getBoolean(mobile_key, false);
	}
   
   public void portrait(View v)
   
   {
  	 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  	
  	  }
  
 }









	   


   



	
	


